<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\ProductRequest;
use App\Models\Category;
use App\Models\OrderProduct;
use App\Models\Product;
use App\Models\ProductSku;
use App\Models\Store;
use Exception;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Throwable;

class ProductController extends Controller
{
    //商品列表
    function index(Request $request){
        //dd(Auth::user()->hasRole('shop'));

        //商品一级分类
        $cates = Category::where('parent_id',0)->orderBy('sort','desc')->get();

        //查询所有开启的商铺
        $stores = Store::where('status',OPEN)->get();
        return view('admin.product.index',['stores'=>$stores,'cates'=>$cates]);
    }

    /** todo    1、添加栏目查询。2、在售显示在售商品的在售型号   下架显示所有商品含有下架型号
     * 列表产品数据接口
     * @param Request $request
     * @return JsonResponse
     */
    public function data(Request $request)
    {
        $model = Product::query();
        if ($request->get('title')){
            $model->where('title','like','%'.$request->get('title').'%');
        }

        //轮播图查询
        if ($is_banner = $request->get('is_banner')){
            if ($is_banner == 1) {//置顶
                $model->where('is_banner','>',0);
            }elseif($is_banner == 2) {//非置顶
                $model->where('is_banner',0);
            }
        }

        $status = $request->get('status');
        //默认查询在售的
        if($status == 1) {
            $model->with('skus')->whereNull('miaosha_start');
        }elseif($status == 2) {//已下架
            $model->onlyTrashed()->with(['skus'=>function($query){
                $query->onlyTrashed();
            }]);
        }else {//查询全部的商品及其规格
            $model->withTrashed()->with(['skus' => function($query){
                $query->withTrashed();
            }]);
        }

        if ($category_id = $request->get('category_id')) {
            $model->where('category_id',$category_id);
        }

        $res = $model->with('category')->orderBy('products.sort','desc')
                    ->orderBy('products.id','desc')
                    ->paginate($request->get('limit',30));
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res->total(),
            'data'  => $res->items(),
        ];
        return Response::json($data);
    }

    /**
     * 添加商品页面
     * @return \Illuminate\Contracts\View\View
     */
    public function create()
    {
        //商品一级分类
        $cates = Category::where('parent_id',0)->orderBy('sort','desc')->get();

        //return $cates;
        //获取开启的商家信息
        $stores = Store::select('id','title')->where('status',2)->get();

        return View::make('admin.product.create',['stores' => $stores,'cates'=>$cates]);
    }

    /**
     * 保存商品
     * @param ProductRequest $request
     * @return RedirectResponse
     */
    public function store(ProductRequest $request)
    {
        //todo  添加商品排序
        $data = $request->validated();

        try{
            DB::transaction(function () use ($data,$request) {
                $product = Product::create($data);
                $product->skus()->createMany($request->post('skus'));
            });
            $this->delete_cache();
            $res_data = [
                'code'      => 0,
                'message'   => '添加成功',
                'data'      => [],
            ];
        }catch (Exception $exception){
            Log::info("添加商品失败：");
            Log::info($exception);
            $res_data = [
                'code'      => 1,
                'message'   => '添加失败',
                'data'      => [],
            ];
        }
        return response()->json($res_data);
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return void
     */
    public function show($id)
    {
        //
    }

    /**
     * 更新商品页面
     * @param $id
     * @return \Illuminate\Contracts\View\View
     */
    public function edit($id)
    {
        //已下架的商品也可以编辑
        $product = Product::with(['skus'=>function($query){
            $query->select('id','product_id','title','origin_price','sold_price','stock')->withTrashed();
        }])->withTrashed()->findOrFail($id);
        //商品的父级栏目
        $parent_id = Category::where(['id'=>$product->category_id])->value('parent_id');
        //商品的同级栏目
        $sibling_categories = Category::where('parent_id',$parent_id)->get();
        foreach ($product['skus'] as $sku) {
            $sku['old_stock'] = $sku['stock'];
        }
        //return $product;
        //商品一级分类
        $cates = Category::where('parent_id',0)->orderBy('sort','desc')->get();

        //获取开启的商家信息
        $stores = Store::select('id','title')->where('status',2)->get();

        return View::make('admin.product.edit',compact('product','stores','cates','parent_id','sibling_categories'));
    }

    /**
     * 更新商品     todo 可单独修改展示销量
     * @param ProductRequest $request
     * @param $id
     * @return RedirectResponse
     * @throws Throwable
     */
    public function update(ProductRequest $request, $id)
    {
        $product = Product::with(['skus'=>function($query){
            //设置关联模型返回指定字段
            $query->select('id','product_id','title','origin_price','sold_price','stock')->withTrashed();
        }])->withTrashed()->findOrFail($id);
        //return $request->all();
        DB::transaction(function () use ($product,$request) {
            $data = $request->validated();
            //todo  更新时添加排它锁，防止库存数据不准。用户打开编辑页面，此时有客户购买商品扣减库存，然后用户提交表单更新，会导致库存不准。
            $product->update($data);

            //不能简单粗暴的删除商品的规格型号信息，会把相应的销量也删掉，同时影响已生成的订单。只能更新规格、新增规格、删除未提交的规格。
            $request_skus = $request->post('skus');
            $skus = json_decode($product['skus'],1);

            //return json_decode($skus,1);
            $product_model = new Product();
            $product_model->update_skus($skus,$request_skus,$product['id']);
        });

        $this->delete_cache();

        $res_data = [
            'code'      => 0,
            'message'   => '更新成功',
            'data'      => [],
        ];

        return  response()->json($res_data);
    }

    //删除商品
    public function destroy(Request $request)
    {
        //商品id数组
        $ids = $request->get('ids');
        if (!is_array($ids) || empty($ids)){
            return Response::json(['code'=>1,'msg'=>'请选择删除项']);
        }
        DB::beginTransaction();
        try{
            //查询该商品是否有订单
            $order_products = OrderProduct::whereIn('product_id',$ids)->get()->toArray();
            //筛选有订单的商品id
            $order_product_ids = array_column($order_products,'product_id');
            //有订单的商品软删除下架，方便以后重新上架。
            Product::whereIn('id',$order_product_ids)->with('skus')->delete();
            ProductSku::whereIn('product_id',$order_product_ids)->delete();
            //没有订单的商品直接删除
            $no_order_product_ids = array_diff($ids,$order_product_ids);
            DB::table('products')->whereIn('id',$no_order_product_ids)->delete();
            DB::table('product_skus')->whereIn('product_id',$no_order_product_ids)->delete();

            DB::commit();
            $this->delete_cache();
            return Response::json(['code'=>0,'msg'=>'删除成功']);
        }catch (Exception $exception){
            Log::info("删除商品失败：");
            Log::info($exception);
            DB::rollback();
            return Response::json(['code'=>1,'msg'=>'删除失败']);
        }
    }

    //下架商品
    function soft_delete(Request $request){
        $request->validate([
            'ids'    =>  'required|array'
        ]);
        DB::beginTransaction();
        try{
            $ids = $request->get('ids');
            Product::destroy($ids);
            ProductSku::whereIn('product_id',$ids)->delete();

            DB::commit();
            $this->delete_cache();
            return Response::json(['code'=>0,'msg'=>'下架成功']);
        }catch (Exception $exception){
            Log::info("下架商品失败：");
            Log::info($exception);
            DB::rollback();
            return Response::json(['code'=>1,'msg'=>'下架失败']);
        }
    }

    //上架商品及其所有规格型号
    function restore(Request $request) {
        $request->validate([
            'ids'    =>  'required|array'
        ]);
        $ids = $request->get('ids');
        $store_ids = Product::whereIn('id',$ids)->pluck('store_id')->toArray();

        if (Store::where('status',CLOSE)->whereIn('id',$store_ids)->first()) {
            return Response::json(['code'=>1,'msg'=>'请先开启商铺']);
        }
        DB::beginTransaction();
        try{
            Product::whereIn('id',$ids)->restore();
            ProductSku::whereIn('product_id',$ids)->restore();

            DB::commit();
            $this->delete_cache();
            return Response::json(['code'=>0,'msg'=>'上架成功']);
        }catch (Exception $exception){
            Log::info("上架商品失败：");
            Log::info($exception);
            DB::rollback();
            return Response::json(['code'=>1,'msg'=>'上架失败']);
        }
    }

    //在操作完商品后，清除一些商品的缓存
    function delete_cache() {
        //删除特价、热销的缓存
        Redis::del('tejia');
        Redis::del('rexiao');
    }
}
